<template>
  <div class="group-send">
    <!-- tabs -->
    <div class="filter-box">
      <!-- 切换tab -->
      <div class="tab-title">
        <p class="can-not-select" :class="{ tabChose: currentTab === 'friendsTab' }" @click="currentTab = 'friendsTab'">
          好友打标签
        </p>
        <p class="can-not-select" :class="{ tabChose: currentTab === 'roomsTab' }" @click="currentTab = 'roomsTab'">
          群打标签
        </p>
      </div>
      <!-- 标签列表 -->
      <ul v-show="!searchContent && currentWeChatId" class="labels-list scroll">
        <!-- 好友 -->
        <template v-if="currentTab === 'friendsTab'">
          <!-- 全选 -->
          <li
            class="label-item"
            :class="{ 'current-label': currentLabel === 'allFriends' }"
            @click="showFriends('allFriends')"
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsChecked.length === toolsFriends.length"
              @click="choseFriendsByLabel($event, 'allFriends')"
            />
            <p v-text="'全部好友'"></p>
          </li>
          <!-- 选择标签 -->
          <li
            v-for="(label, index) in toolsLabels"
            :key="index"
            class="label-item"
            :class="[
              { 'current-label': currentLabel === label.LabelId },
              {
                'label-disabled': !friendsOfEveryLabel[label.LabelId] || friendsOfEveryLabel[label.LabelId].length === 0
              }
            ]"
            @click="
              friendsOfEveryLabel[label.LabelId] && friendsOfEveryLabel[label.LabelId].length === 0
                ? ''
                : showFriends(label.LabelId)
            "
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="
                friendsOfEveryLabel[label.LabelId] &&
                  friendsOfEveryLabel[label.LabelId].length !== 0 &&
                  friendsOfEveryLabel[label.LabelId].length === friendsCheckedByLabel[label.LabelId].length
              "
              @click="choseFriendsByLabel($event, label.LabelId)"
            />
            <p class="ellipsis">
              {{ label.LabelName }}({{
                friendsOfEveryLabel[label.LabelId] ? friendsOfEveryLabel[label.LabelId].length : 0
              }})
            </p>
          </li>
        </template>
        <!-- 群 -->
        <template v-else>
          <!-- 全选 -->
          <li
            class="label-item"
            :class="{ 'current-label': currentRoomLabel === 'allFriends' }"
            @click="showFriends('allFriends')"
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="roomsChecked.length === toolsRooms.length"
              @click="choseRoomsByLabel($event, 'allFriends')"
            />
            <p v-text="'全部群组'"></p>
          </li>
        </template>
      </ul>
      <!-- 新建标签 -->
      <el-button
        v-if="currentWeChatId"
        class="create-label"
        size="small"
        type="text"
        plain
        icon="el-icon-plus"
        @click="createLabel"
      >
        新建标签
      </el-button>
    </div>

    <!-- 好友列表 -->
    <div v-if="currentTab === 'friendsTab'" class="friends-list">
      <!-- search -->
      <div class="friends-list-title">
        <p>好友列表</p>
        <!-- 搜索 -->
        <el-input
          v-model.lazy="searchContent"
          class="search-input"
          size="small"
          suffix-icon="el-icon-search"
          type="text"
          placeholder="输入昵称搜索"
        ></el-input>
      </div>
      <!-- table -->
      <el-table v-if="forceRefresh" class="scroll" :data="tableDataPage[currentPage - 1]" stripe>
        <el-table-column type="index" :index="indexMethod" label="序号" width="60px"></el-table-column>
        <el-table-column label="昵称" prop="FriendNick"></el-table-column>
        <el-table-column label="头像" width="60px" style="border: solid red 1px">
          <template slot-scope="scope">
            <el-image style="width: 30px; height: 30px" :src="scope.row.Avatar">
              <div slot="error" class="image-slot">
                <i style="font-size: 30px" class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="备注名" prop="Memo"></el-table-column>
        <el-table-column width="100px">
          <template slot="header"></template>
          <template slot-scope="scope">
            <input
              v-if="currentLabel === 'allFriends'"
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsChecked.indexOf(scope.row.FriendId) >= 0"
              @click="choseFriend($event, scope.row)"
            />
            <input
              v-else
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsCheckedByLabel[currentLabel].indexOf(scope.row.FriendId) >= 0"
              @click="choseFriend($event, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin: 5px auto 0"
        :current-page="currentPage"
        :page-sizes="[50, 100, 150, 200]"
        :page-size="pageSize"
        :pager-count="7"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 群列表 -->
    <ul v-else class="chat-rooms-list scroll">
      <li
        v-for="(room, index2) in toolsRooms"
        :key="index2"
        class="room-item"
        :class="{ 'room-item-3x': index2 % 3 === 2 }"
      >
        <el-avatar style="min-width: 34px; margin-right: 5px" :size="34" shape="square" :src="room.Avatar">
          <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
        </el-avatar>
        <p class="ellipsis" v-text="room.NickName"></p>
        <input type="checkbox" :checked="roomsChecked.indexOf(room.UserName) >= 0" @click="choseRoom($event, room)" />
      </li>
    </ul>

    <!-- 展示已选的好友|群 -->
    <div class="friends-chosed">
      <!-- 统计 -->
      <div class="third-box-title">
        <p style="color: #999999" v-text="currentTab === 'friendsTab' ? '已选好友' : '已选群组'"></p>
        <p v-if="currentTab === 'friendsTab'">
          已选
          <span style="color: #ff0000" v-text="finalFriendsInfo.length"></span>
          人
        </p>
        <p v-else>
          已选
          <span style="color: #ff0000" v-text="roomsChecked.length"></span>
          个
        </p>
      </div>

      <!-- 展示数据 -->
      <div class="friends-chose-list scroll">
        <el-tag
          v-for="(friend, index) in currentTab === 'friendsTab' ? finalFriendsInfo : roomsCheckedInfo"
          :key="index"
          style="margin: 5px"
          closable
          type="info"
          @close="currentTab === 'friendsTab' ? removeFriend(friend) : removeRoom(friend)"
        >
          {{ friend.FriendNick || friend.NickName }}
        </el-tag>
      </div>

      <!-- 选中要打的标签 -->
      <el-select v-model="labelId2Send" style="margin: 5px" size="small" clearable placeholder="请选择标签">
        <el-option
          v-for="(tl, index) in toolsLabels"
          :key="index"
          :label="tl.LabelName"
          :value="tl.LabelId"
        ></el-option>
      </el-select>

      <!-- 打标签 -->
      <div class="friends-chosed-btns">
        <el-button style="background-color: #ff9f00; color: white; width: 178px" size="small" @click="takeLabel">
          贴标签
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { uniqueArryList } from '@/utils/util.js'

export default {
  data() {
    return {
      searchContent: '', // 搜索框的内容
      currentTab: 'friendsTab', // 默认是群发好友
      currentLabel: 'allFriends', // 要展示的好友标签
      tableData: [], // 表数据 默认展示全部的好友
      friendsChecked: [], // 已选择的好友的id
      friendsCheckedByLabel: {}, // 每个label选中的好友
      finalFriends: [], // 计算最终选中的好友
      labelId2Send: [], // 要打的标签id
      forceRefresh: true, // 重新渲染表格 强制数据刷新
      friendsOfEveryLabel: {}, // 每个label的好友

      currentRoomLabel: 'allFriends', // 要展示的好友标签
      roomsChecked: [], // 选择的群
      currentPage: 1,
      pageSize: 50
    }
  },
  computed: {
    ...mapState('nedb', {
      toolsLabels: 'toolsLabels',
      toolsRooms: 'toolsRooms'
    }),
    ...mapGetters({
      currentWeChatId: 'tools/currentWeChatId',
      toolsFriends: 'nedb/toolsFriends',
      toolsLabelIdMap: 'nedb/toolsLabelIdMap'
    }),
    // 选择的好友
    finalFriendsInfo() {
      const ffi = []
      this.toolsFriends.forEach((x) => {
        if (this.finalFriends.indexOf(x.FriendId) >= 0) {
          ffi.push(x)
        }
      })
      return ffi
    },
    // 选中的群的信息
    roomsCheckedInfo() {
      const ffi = []
      this.toolsRooms.forEach((x) => {
        if (this.roomsChecked.indexOf(x.UserName) >= 0) {
          ffi.push(x)
        }
      })
      return ffi
    },
    // 表数据分页展示
    tableDataPage() {
      // 分页 每页50
      const size = this.pageSize
      const newData = []
      for (let i = 0; i < this.tableData.length; i += size) {
        newData.push(this.tableData.slice(i, i + size))
      }
      return newData
    }
  },
  watch: {
    // 监听搜索栏
    searchContent(sc) {
      if (sc) {
        this.tableData = this.toolsFriends.filter((x) => {
          // 昵称
          if (x.FriendNick) {
            return x.FriendNick.indexOf(this.searchContent) >= 0
          }
          // 备注
          if (x.Memo) {
            return x.Memo.indexOf(this.searchContent) >= 0
          }
          // 群名
          if (x.NickName) {
            return x.NickName.indexOf(this.searchContent) >= 0
          }
          // 陌生人
          if (x.Nickname) {
            return x.Nickname.indexOf(this.searchContent) >= 0
          }
        })
      } else {
        this.tableData = this.toolsFriends
      }
    },
    // 监听微信改变
    currentWeChatId(newId) {
      this.currentLabel = 'allFriends'
      this.currentRoomLabel = 'allFriends'
      setTimeout(() => {
        if (newId) {
          this.tableData = this.toolsFriends
        } else {
          this.tableData = []
        }
        setTimeout(() => {
          this.initData()
        }, 200)
      }, 100)
    }
    // toolsLabels() {
    //   setTimeout(() => {
    //     this.initData()
    //   }, 500)
    // }
  },
  created() {
    if (this.currentWeChatId) {
      // 设置好友
      this.$store.dispatch('nedb/SetToolsFriends', this.currentWeChatId)
      // 设置群聊
      this.$store.dispatch('nedb/SetToolsRooms', this.currentWeChatId)
      // 设置labels
      this.$store.dispatch('nedb/SetToolsLabels', this.currentWeChatId)
      setTimeout(() => {
        this.initData()
      }, 200)
    }
  },
  methods: {
    // 改pageSize
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 新建标签
    createLabel() {
      if (!this.currentWeChatId) {
        this.$alert('请先选中微信！', '提示', { type: 'warning' })
        return
      }
      this.$prompt('请输入标签名', '新建标签', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S{1,20}?/,
        inputErrorMessage: '标签名不符合要求！'
      })
        .then(({ value }) => {
          const msg = {
            WeChatId: this.currentWeChatId, // 商家所属微信号
            LabelId: 0, // 标签id，0则新建标签（如存在同名标签则会失败）
            LabelName: value // 标签名 id!=0 会设置为该标签名
          }
          this.$store.dispatch('websocket/ContactLabelTask', msg)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    },
    // 打标签
    takeLabel() {
      if (this.currentTab === 'friendsTab') {
        if (!this.currentWeChatId) {
          this.$alert('请先选中微信！', '提示', { type: 'warning' })
          return
        }
        if (!this.labelId2Send || !this.toolsLabelIdMap[this.labelId2Send]) {
          this.$alert('请选择要打的标签！', '提示', { type: 'warning' })
          return
        }
        if (this.finalFriends.length === 0) {
          this.$alert('请选择好友！', '提示', { type: 'warning' })
          return
        }
        const msg = {
          WeChatId: this.currentWeChatId, // 商家所属微信号
          AddList: this.finalFriends.join(','), // 新增的wxid，用,分隔
          LabelId: this.labelId2Send, // 标签id，0则新建标签（如存在同名标签则会失败）
          LabelName: this.toolsLabelIdMap[this.labelId2Send] // 标签名 id!=0 会设置为该标签名
          // DelList: 5, // 删除的wxid，用,分隔
          // taskId: 6,
        }
        this.$store.dispatch('websocket/ContactLabelTask', msg)
        this.$parent.resetWeChatId()
      } else {
        this.$alert('给群打标签,请自行实现!', '提示', { type: 'info' })
      }
    },
    // 初始化数据
    initData() {
      this.tableData = this.toolsFriends
      for (const label of this.toolsLabels) {
        this.friendsOfEveryLabel[label.LabelId] = this.toolsFriends.filter((x) => {
          return x.LabelIds && x.LabelIds.indexOf(String(label.LabelId)) >= 0
        })
        this.friendsCheckedByLabel[label.LabelId] = []
      }
      this.$nextTick()
      this.$forceUpdate()
    },
    // 计算序号
    indexMethod(index) {
      return index + 1
    },
    // 展示数据
    showFriends(labelId) {
      if (labelId === 'allFriends') {
        this.tableData = this.toolsFriends
      } else {
        this.tableData = this.toolsFriends.filter((x) => {
          return x.LabelIds && x.LabelIds.indexOf(String(labelId)) >= 0
        })
      }
      this.currentLabel = labelId
    },
    // 计算选中的好友
    computedFriends() {
      let cfs = [].concat(this.friendsChecked)
      for (const key in this.friendsCheckedByLabel) {
        if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
          cfs = cfs.concat(this.friendsCheckedByLabel[key])
        }
      }
      this.finalFriends = uniqueArryList(cfs, 'FriendId')
    },
    // 选中标签
    choseFriendsByLabel(e, labelId) {
      if (labelId === 'allFriends') {
        if (this.friendsChecked.length === this.toolsFriends.length) {
          // 全不选
          this.friendsChecked = []
          // 重置每个label的选中的微信
          for (const key in this.friendsCheckedByLabel) {
            if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
              this.friendsCheckedByLabel[key] = []
            }
          }
        } else {
          // 全选
          this.toolsFriends.forEach((x) => {
            if (this.friendsChecked.indexOf(x.FriendId) < 0) {
              this.friendsChecked.push(x.FriendId)
            }
          })
          // 全选每个label的好友
          for (const key in this.friendsOfEveryLabel) {
            if (Object.hasOwnProperty.call(this.friendsOfEveryLabel, key)) {
              const element = this.friendsOfEveryLabel[key]
              this.friendsCheckedByLabel[key] = element.map((x) => {
                return x.FriendId
              })
            }
          }
        }
      } else {
        if (this.friendsOfEveryLabel[labelId].length === 0) {
          e.preventDefault()
          return
        }
        const currentFriends = this.friendsOfEveryLabel[labelId]
        const currentChoseFriends = this.friendsCheckedByLabel[labelId]
        if (currentFriends.length === currentChoseFriends.length) {
          this.friendsCheckedByLabel[labelId] = []
        } else {
          currentFriends.forEach((x) => {
            if (currentChoseFriends.indexOf(x.FriendId) < 0) {
              currentChoseFriends.push(x.FriendId)
            }
          })
        }
      }
      this.computedFriends()
    },
    // table中的单选
    choseFriend(e, friend) {
      const friendId = friend.FriendId
      const labelId = this.currentLabel
      if (this.currentLabel === 'allFriends') {
        const fid = this.friendsChecked.indexOf(friendId)
        if (fid >= 0) {
          // 移除
          this.friendsChecked.splice(fid, 1)
        } else {
          // 添加
          this.friendsChecked.push(friendId)
        }
      } else {
        const fid = this.friendsCheckedByLabel[labelId].indexOf(friendId)
        if (fid >= 0) {
          // 移除
          this.friendsCheckedByLabel[labelId].splice(fid, 1)
        } else {
          // 添加
          this.friendsCheckedByLabel[labelId].push(friendId)
        }
        // 重新渲染组件
        this.$forceUpdate()
      }
      this.computedFriends()
    },
    // 群聊 选中标签
    choseRoomsByLabel(e, labelId) {
      if (labelId === 'allFriends') {
        if (this.roomsChecked.length === this.toolsRooms.length) {
          // 全不选
          this.roomsChecked = []
        } else {
          // 全选
          this.toolsRooms.forEach((x) => {
            if (this.roomsChecked.indexOf(x.UserName) < 0) {
              this.roomsChecked.push(x.UserName)
            }
          })
        }
      }
    },
    // 选择群聊
    choseRoom(e, room) {
      const rid = this.roomsChecked.indexOf(room.UserName)
      if (this.currentRoomLabel === 'allFriends') {
        if (rid >= 0) {
          // 移除
          this.roomsChecked.splice(rid, 1)
        } else {
          // 添加
          this.roomsChecked.push(room.UserName)
        }
      }
    },
    // 移除选择的好友
    removeFriend(friend) {
      const friendId = friend.FriendId
      const fid = this.friendsChecked.indexOf(friendId)
      // 移除friendsChecked中的数据
      if (fid >= 0) {
        this.friendsChecked.splice(fid, 1)
      }
      this.forceRefresh = false
      // 移除每个label的选择
      for (const key in this.friendsCheckedByLabel) {
        if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
          const fcd = this.friendsCheckedByLabel[key]
          const fcdid = fcd.indexOf(friendId)
          if (fcdid >= 0) {
            fcd.splice(fid, 1)
          }
        }
      }
      setTimeout(() => {
        this.forceRefresh = true
      }, 50)
      // 重新渲染组件
      this.$forceUpdate()
      // 重新计算选择的好友
      this.computedFriends()
    },
    // 移除room
    removeRoom(room) {
      this.roomsChecked.splice(this.roomsChecked.indexOf(room.UserName), 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.group-send {
  flex: 1 1 auto;
  display: flex;
  overflow: hidden;

  .filter-box {
    width: 189px;
    min-width: 189px;
    height: 100%;
    padding: 5px 5px 0 5px;
    border: solid #eeeeee 1px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .tab-title {
      width: 100%;
      display: flex;
      p {
        width: 50%;
        height: 40px;
        color: #999999;
        font-size: 14px;
        line-height: 40px;
        font-weight: 500;
        cursor: pointer;
        text-align: center;
        border-bottom: solid #dddddd 1px;
      }
      .tabChose {
        color: #ff9f00;
        border-bottom: solid #ff9f00 1px;
      }
    }

    .labels-list {
      width: 100%;
      flex: 1 1 auto;
      overflow: auto;

      .label-item {
        display: flex;
        align-items: center;
        color: #333333;
        font-size: 14px;
        height: 26px;
        cursor: pointer;
        p {
          margin-left: 5px;
          width: 150px;
          height: 26px;
          line-height: 26px;
        }
      }
      .current-label {
        color: #ff9f00;
      }
      .label-disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        input {
          cursor: not-allowed;
          color: #c0c4cc;
          border: solid #c0c4cc 1px;
        }
      }
    }

    ::v-deep .create-label {
      color: #576c95;
      align-self: center;
      font-size: 12px;
      width: 120px;
      padding: 5px;
      margin: 5px 0;
      border: 1px dashed #dadada;
      // border: solid red 1px;
    }
  }

  .friends-list {
    width: 722px;
    height: 100%;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .friends-list-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 0 10px 0;
      p {
        font-size: 14px;
        color: #999999;
      }
      .search-input {
        width: 200px;
        height: 32px;
        // .el-input__inner {
        //   height: 28px;
        //   line-height: 28px;
        //   color: #dadada;
        //   font-size: 12px;
        //   padding-left: 5px;
        // }
      }
    }

    ::v-deep .el-table {
      width: 100%;
      height: 100%;
      overflow: auto;
      .el-table__header-wrapper {
        min-height: 40px;
        display: flex;
        align-items: center;
        background-color: #ff9f000d;

        .el-table__header {
          th {
            background-color: #ff9f000d;
            padding: 0;
            border-bottom: none;
          }
        }
      }
      td {
        padding: 5px;
      }
    }
  }

  .chat-rooms-list {
    flex: 1 1 auto;
    padding: 14px;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .room-item {
      width: 192px;
      height: 58px;
      border-radius: 5px;
      margin: 0 15px 15px 0;
      background-color: #f7f7f5;
      display: flex;
      align-items: center;
      padding: 0 17px;
      p {
        width: 150px;
      }
    }
    .room-item-3x {
      margin-right: 0;
    }
  }

  .friends-chosed {
    width: 209px;
    min-width: 209px;
    display: flex;
    flex-direction: column;
    border-left: solid #eeeeee 1px;

    .third-box-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      color: #333333;
      padding: 5px;
      height: 40px;
      line-height: 40px;
      // border: solid red 1px;
    }
    .friends-chose-list {
      flex: 1 1 auto;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
    }
    .friends-chosed-btns {
      height: 50px;
      min-height: 50px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f9f9f9;
      .el-button {
        width: 82px;
        height: 32px;
      }
    }
  }
}
</style>

